#include "ADC.h"
#include "project.h"

uint8_t readAdc(uint8_t adcPin) {

	ADMUX &= 0xF0;						//Clear the older channel that was read
	ADMUX |= adcPin;					//Defines the new ADC channel to be read
	ADCSRA |= (1 << ADSC);				//Starts a new conversion
	while (ADCSRA & (1 << ADSC)) {
	}		//wait while converter busy
	return ADCW ;

}

uint8_t getPushButton(uint8_t adcChannel) {

	static uint8_t buttonNew = 0, buttonOld = 6;
	uint8_t pbVal;
	pbVal = readAdc(pbPin);

	if (pbVal > 30 && (buttonNew != buttonOld)) {

		pbVal = 20 * readAdc(pbPin);
		if ((pbVal > 800) && (pbVal < 1300)) buttonNew = up;

		else if ((pbVal > 1600) && (pbVal < 2200)) buttonNew = down;

		else if ((pbVal > 3000) && (pbVal < 3500)) buttonNew = left;

		else if ((pbVal > 3800) && (pbVal < 4200)) buttonNew = right;

		else if ((pbVal > 4500) && (pbVal < 5000)) buttonNew = action;
		else buttonNew = none;
		_delay_ms(2);
		return buttonNew;
	}
	return 0;

}
uint8_t buttonNew = 0, buttonOld = 6;

void initAdc(uint8_t adcPin) {

	ADCSRA |= ((1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0));    //per datasheet, 16Mhz/128(prescale)=125Khz the ADC reads
	ADMUX |= (1 << REFS0);		//use 5vVref
	ADCSRA |= (1 << ADEN);		//enable adc free run mode
	ADCSRA |= (1 << ADSC);

}
